package com.playmoney.command;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.followman.framework.BeanFactory;
import com.followman.framework.FrameWork;
import com.followman.framework.RequestService;
import com.followman.framework.ResponseService;
import com.followman.framework.command.Command;

import freemarker.template.Template;
import freemarker.template.TemplateException;

public class DispatcherAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8021118497758559497L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Pattern fullModulePattern =Pattern.compile("^/(\\w+)/(\\w+?)\\.");
		Pattern actionPattern =Pattern.compile("^/(\\w+?)\\.");
		
		RequestService request=new RequestService(req);
		String contextPath=request.getContextPath();
		String module="default";
		String action="index";
		String path=request.getRequestURI().replace(contextPath, "");		 
		Matcher mc=fullModulePattern.matcher(path);		
		if(mc.find()){
			//这里是匹配了
			module=mc.group(1);
			action=mc.group(2);
		}else{
			mc=actionPattern.matcher(path);
			if(mc.find()){
				action=mc.group(1);
			}
		}
		ResponseService response=new ResponseService(resp);
		request.changeModule(module);
		request.changeAction(action);	
		Command command =BeanFactory.getBean(request.getModule(),Command.class);
		HashMap<String,Object> context=new HashMap<String,Object>();
		context.put("theme", FrameWork.getPropertiesHolder().getProperty("theme.default", "default"));
		context.put("contextPath",contextPath);
		context.put("version", FrameWork.getPropertiesHolder().getProperty("application.version", "V1.0.0.0"));
		context.put("datetime", new Date().getTime());
		response.setHeader("Pragma","No-cache");
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires", -10);
		response.setCharacterEncoding("utf-8");
		if(command!=null){			
			Template template=command.execute(context, request, response);
			if(template!=null){
				try {
					template.process(context, response.getWriter());
				} catch (TemplateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}	
	}

}
